import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:pocketfile/module/home/controller/home_controller.dart';
import 'package:pocketfile/module/home/entity/device_entity.dart';
import 'package:pocketfile/module/home/utils/socket_tcp_utils.dart';

class DeviceWidget extends StatelessWidget {
  late final DeviceEntity _deviceEntity;

  DeviceWidget(this._deviceEntity, {Key? key}) : super(key: key);
  HomeController _homeController = Get.put(HomeController());

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    print('构建DeviceWidget');
    return GestureDetector(
      onTap: () {
        _sendFile(_deviceEntity);
      },
      child: Column(
        children: [
          Image.asset(
            "assets/device_icon.png",
            width: 50,
            height: 50,
            fit: BoxFit.fill,
          ),
          Text(_deviceEntity.name),
        ],
      ),
    );
  }

  void _sendFile(DeviceEntity deviceEntity) async {
    //往下开始用filepick提供的方法
    FilePickerResult? result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: ['jpg', 'pdf', 'doc'],
        withData: true);
    //这就用完了，下面就赋值了
    if (result != null) {
      PlatformFile file = result.files.first;
      print("dddd ${file.path}");
      print("dddd ${file.name}");
      print("dddd ${file.extension}");

      print("dddd ${file.size}");
      List<int> dataList = [];
      //封包
      dataList.add("\$".codeUnitAt(0));
      dataList.add(file.name.codeUnits.length); //名字长度最多一个字节超出255截断
      dataList.addAll(file.name.codeUnits); //名字长度最多一个字节超出255截断
      dataList.add((file.size & 0xFF000000) >> 24);
      dataList.add((file.size & 0x00FF0000) >> 16);
      dataList.add((file.size & 0x0000FF00) >> 8);
      dataList.add((file.size & 0x000000FF));
      dataList.addAll(file.bytes!);
      dataList.add("&".codeUnitAt(0));
      print('${file.bytes.toString()}      ${file.name}');
      _homeController.pushFile(dataList, deviceEntity);
    } else {
      // User canceled the picker
      print('取消了文件选择器');
    }
  }
}
